import 'package:flutter/material.dart';
import 'package:pp_uikit/bottom_sheet/pp_action_sheet_theme.dart';
import 'package:pp_uikit/bottom_sheet/pp_common_action_sheet_item.dart';
import 'package:pp_uikit/theme/pp_default_theme.dart';

/// 吸底列表弹框，可自定义标题文案
/// 可通过配置[PPCommonActionSheetItemStyle]来设定 item 的样式
// ignore: must_be_immutable
class PPImageSingleSelectionActionSheet extends StatelessWidget {
  /// 每个选项相关的配置信息的列表
  /// 每个选项支持修改内容见[PPCommonActionSheetItem]
  final List<PPCommonActionSheetItem> actions;

  /// Action 之间分割线颜色，默认值 Color(0xfff0f0f0)
  final Color? separatorLineColor;

  /// 取消按钮与 Action 之间的分割线的颜色，默认值 Color(0xfff8f8f8)
  final Color spaceColor;

  /// 取消按钮文本
  final String? cancelTitle;

  /// 标题最大行数，默认为2
  final int maxTitleLines;

  /// 列表最大高度限制，默认为屏幕高度减去上下安全距离
  /// 默认为0
  final double maxSheetHeight;

  /// Action Item 的点击事件
  final PPCommonActionSheetItemClickCallBack? clickCallBack;

  /// Action Item 点击事件拦截回调
  final PPCommonActionSheetItemClickInterceptor? onItemClickInterceptor;

  /// 主题定制
  PPActionSheetTheme? themeData;

  PPImageSingleSelectionActionSheet({
    super.key,
    required this.actions,
    this.cancelTitle,
    this.clickCallBack,
    this.separatorLineColor,
    this.spaceColor = Colors.white,
    this.maxTitleLines = 2,
    this.maxSheetHeight = 0,
    this.onItemClickInterceptor,
    this.themeData,
  }) {
    themeData ??= PPActionSheetTheme();
  }

  @override
  Widget build(BuildContext context) {
    EdgeInsets padding = MediaQueryData.fromView(View.of(context)).padding;
    double maxHeight =
        MediaQuery.of(context).size.height - padding.top - padding.bottom;

    double maxSheetHeight = 0;

    if (maxSheetHeight <= 0 || maxSheetHeight > maxHeight) {
      maxSheetHeight = maxHeight;
    }
    return GestureDetector(
      child: Container(
          decoration: ShapeDecoration(
            color: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(themeData!.topRadius),
                topRight: Radius.circular(themeData!.topRadius),
              ),
            ),
          ),
          child:
              SafeArea(child: _configActionWidgets(context, maxSheetHeight))),
      onVerticalDragUpdate: (v) => {},
    );
  }

  /// 构建actionSheet的按钮
  Widget _configActionWidgets(BuildContext context, double maxSheetHeight) {
    List<Widget> widgets = [];

    widgets.add(const SizedBox(height: 8));
    widgets.add(_configListActions(context));
    // 添加间隔
    widgets.add(Divider(
      color: spaceColor,
      thickness: 8,
      height: 8,
    ));
    widgets.add(_configCancelAction(context));

    return Container(
      constraints: BoxConstraints(maxHeight: maxSheetHeight),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: widgets,
      ),
    );
  }

  /// 构建列表widget
  Widget _configListActions(BuildContext context) {
    List<Widget> tiles = [];
    //构建列表内容
    for (int index = 0; index < actions.length; index++) {
      tiles.add(
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          child: Container(
            padding: themeData!.contentPadding,
            child: _configTile(actions[index]),
          ),
          onTap: () {
            if (onItemClickInterceptor == null ||
                !onItemClickInterceptor!(index, actions[index])) {
              // 如果未拦截，则pop掉当前页面，并且携带信息（不建议使用此信息进行点击时间处理）
              Navigator.of(context).pop([index, actions[index]]);
              // 推荐使用回调方法处理点击事件!!!!!!!!!!
              if (clickCallBack != null) {
                clickCallBack!(index, actions[index]);
              }
            }
          },
        ),
      );
    }
    return Flexible(
      child: ListView(
        physics: const BouncingScrollPhysics(),
        shrinkWrap: true,
        children: tiles,
      ),
    );
  }

  // 配置每个选项内部信息
  // action 每个item配置项 [PPCommonActionSheetItem]
  Widget _configTile(PPCommonActionSheetItem action) {
    List<Widget> tileElements = [];
    // 添加标题
    tileElements.add(Row(
      children: [
        if (action.image != null)
          Image.asset(
            "${action.image}",
            fit: BoxFit.cover,
            height: themeData!.imageSize.height,
            width: themeData!.imageSize.width,
          ),
        const SizedBox(width: PPDefaultTheme.hSpacingSm),
        Text(
          action.title,
          maxLines: 1,
          style: action.titleStyle ??
              (action.actionStyle == PPCommonActionSheetItemStyle.alert
                  ? themeData!.itemTitleStyleAlert
                  : (action.actionStyle == PPCommonActionSheetItemStyle.selected
                      ? themeData!.itemTitleStyleLink
                      : themeData!.itemTitleStyle)),
        ),
      ],
    ));
    // 如果有辅助信息则添加辅助信息
    if (action.desc != null) {
      tileElements.add(const SizedBox(height: 2));
      tileElements.add(
        Center(
          child: Text(
            action.desc!,
            textAlign: TextAlign.center,
            maxLines: 1,
            style: action.descStyle ??
                (action.actionStyle == PPCommonActionSheetItemStyle.alert
                    ? themeData!.itemDescStyleAlert
                    : (action.actionStyle ==
                            PPCommonActionSheetItemStyle.selected
                        ? themeData!.itemDescStyleLink
                        : themeData!.itemDescStyle)),
          ),
        ),
      );
    }
    return Column(
        crossAxisAlignment: CrossAxisAlignment.start, children: tileElements);
  }

  /// 构建取消操作按钮
  Widget _configCancelAction(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        Navigator.of(context).pop();
      },
      child: Container(
        margin: const EdgeInsets.only(top: 12, left: 12, right: 12),
        padding: const EdgeInsets.only(top: 12, bottom: 12),
        decoration: BoxDecoration(
          color: PPDefaultTheme.instance.backgroundColor,
          borderRadius: const BorderRadius.all(Radius.circular(21)),
        ),
        child: Center(
          child: Text(
            cancelTitle ?? "取消",
            style: themeData!.cancelStyle,
          ),
        ),
      ),
    );
  }
}
